#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/15 22:23
# @Author : cjw
import requests
import allure
from requests.models import Response
from typing import Optional

from server_task.util.log import logger


class BaseApi:

    def request(self, data: dict) -> Response:
        """
        发送请求
        :param data: 请求的数据
        :return:
        """
        # 为了多协议支持，或者将来协议变更，或者将来方便切换不同的http库
        if 'url' in data:
            return next(self._http_request(data))

    def _http_request(self, data: dict) -> Response:
        """
        发送http请求, 返回响应后，再关闭http连接
        :param data: 请求数据
        :return:
        """
        rsp: Optional[Response] = None
        try:
            with allure.step(msg := f'发送请求：{data.get("url")}'):
                logger.info(msg)
                rsp = requests.request(**data)
            with allure.step(msg := f'响应结果：{rsp.json()}'):
                logger.info(msg)
            yield rsp
        except Exception as e:
            with allure.step(msg := f'请求异常：{e}'):
                logger.info(msg)
                raise e
        finally:
            with allure.step(msg := f'关闭连接：{rsp.url}'):
                logger.info(msg)
                rsp.close()
